package com.sunny.structure.stack;

import com.sunny.structure.lineartable.singlelinked.ListNode;

/**
 * @author Sunny
 * @date 2020/5/21
 */
public class MyStack {
    private ListNode stackTop;
    private ListNode stackBottom;

    public MyStack(ListNode stackTop, ListNode stackBottom) {
        this.stackTop = stackTop;
        this.stackBottom = stackBottom;
    }

    /**
     * 压栈
     */
    public static void pushStack(MyStack myStack, int value) {
        ListNode node = new ListNode(value);
        node.next = myStack.stackTop;
        myStack.stackTop = node;
    }

    public static boolean isEmpty(MyStack myStack) {
        return myStack.stackTop == myStack.stackBottom;
    }

    /**
     * 弹栈
     */
    public static ListNode popStack(MyStack myStack) {
        if (!isEmpty(myStack)) {
            ListNode stackTop = myStack.stackTop;
            myStack.stackTop = stackTop.next;
            return stackTop;
        }
        return null;
    }

    /**
     * 遍历
     *  栈顶指针不指向栈底即可以继续遍历
     */
    public static void traversStack(MyStack myStack) {
        ListNode stackTop = myStack.stackTop;
        while (stackTop != myStack.stackBottom) {
            System.out.print(stackTop.value + " ");
            stackTop = stackTop.next;
        }
        System.out.println();
    }

    public static void clearStack(MyStack myStack) {
        myStack.stackTop = null;
        //栈底指向栈顶,表示为空
        myStack.stackBottom = myStack.stackTop;
    }

    public static void main(String[] args) {
        MyStack stack = new MyStack(new ListNode(0), new ListNode(0));
        stack.stackTop = stack.stackBottom;

        System.out.println(isEmpty(stack));

        pushStack(stack, 1);
        pushStack(stack, 2);
        pushStack(stack, 3);

        traversStack(stack);

        System.out.println(isEmpty(stack));
        System.out.println(popStack(stack).value);

        clearStack(stack);

        System.out.println(isEmpty(stack));
    }
}
